<template>
  <div class="profile-container">
    <!-- 顶部用户信息区域 -->
    <div class="user-header">
      <div class="user-info">
        <div class="avatar" @click="handleAvatarClick">
          <input
            type="file"
            ref="fileInput"
            accept="image/*"
            style="display: none"
            @change="handleFileChange"
          />
          <img :src="avatarUrl" alt="用户头像" />
          <div v-if="isUploading" class="avatar-loading">
            <span>上传中...</span>
          </div>
        </div>
        <div class="user-details">
          <h2>{{ username || '游客' }}</h2>
          <p class="user-id">会员ID: {{ userId || '未登录' }}</p>
        </div>
      </div>
      <div class="setting-icon" @click="set">
        <i>⚙️</i>
      </div>
    </div>

    <!-- 会员卡区域 -->
    <div class="member-card">
      <div class="card-content">
        <div class="card-logo">
          <span class="logo-text">Ludy Coffee</span>
        </div>
        <div class="card-info">
          <div class="points">
            <span class="point-value">{{ points }}</span>
            <span class="point-label">咖啡豆</span>
          </div>
          <div class="level">
            <span class="level-value">{{ level }}</span>
            <span class="level-label">会员等级</span>
          </div>
        </div>
        <div class="card-bottom">
          <span class="card-number">{{ cardNumber }}</span>
        </div>
      </div>
    </div>

    <!-- 订单记录 -->
    <div class="order-section">
      <div class="section-header">
        <h3>我的订单</h3>
        <span class="view-all">查看全部 ></span>
      </div>
      <div class="order-status">
        <div class="status-item" @click="payment">
          <div class="status-icon">🛒</div>
          <div class="status-text">待付款</div>
        </div>
        <div class="status-item">
          <div class="status-icon">🛍️</div>
          <div class="status-text">待取餐</div>
        </div>
        <div class="status-item" @click="over">
          <div class="status-icon">🥤</div>
          <div class="status-text">已完成</div>
        </div>
        <div class="status-item" @click="appraise">
          <div class="status-icon">⭐</div>
          <div class="status-text">待评价</div>
        </div>
      </div>
    </div>

    <!-- 功能菜单 -->
    <div class="function-menu">
      <div class="menu-item" @click="Coupons">
        <div class="menu-icon">🎁</div>
        <div class="menu-text">优惠券</div>
      </div>
      <div class="menu-item" @click="Integral">
        <div class="menu-icon">💰</div>
        <div class="menu-text">积分商城</div>
      </div>
      <div class="menu-item" @click="member">
        <div class="menu-icon">🏆</div>
        <div class="menu-text">会员特权</div>
      </div>
      <div class="menu-item" @click="addresstwo">
        <div class="menu-icon">📍</div>
        <div class="menu-text">收货地址</div>
      </div>
    </div>

    <!-- 设置菜单 -->
    <div class="settings-menu">
      <div class="section-header">
        <h3>设置与服务</h3>
      </div>
      <div class="settings-list">
        <div class="settings-item" @click="message">
          <span class="item-name">消息通知</span>
          <span class="item-arrow">></span>
        </div>
        <div class="settings-item" @click="Translation">
          <span class="item-name">帮助中心</span>
          <span class="item-arrow">></span>
        </div>
        <div class="settings-item" @click="navigateToAddress">
          <span class="item-name">地址管理</span>
          <span class="item-arrow">></span>
        </div>
        <div class="settings-item" @click="About">
          <span class="item-name">关于我们</span>
          <span class="item-arrow">></span>
        </div>
        <div class="settings-item" @click="handleLogout">
          <span class="item-name logout">退出登录</span>
          <span class="item-arrow">></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const username = ref('')
const userId = ref('')
const points = ref('286')
const level = ref('银卡会员')
const cardNumber = ref('6235 **** **** 3291')

// 新增的头像相关变量和方法
const fileInput = ref<HTMLInputElement | null>(null)
const avatarUrl = ref('https://placekitten.com/100/100')
const isUploading = ref(false)

const handleAvatarClick = () => {
  fileInput.value?.click()
}

const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (file) {
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件')
      return
    }

    // 创建图片对象以获取尺寸
    const img = new Image()
    const reader = new FileReader()

    reader.onload = (e) => {
      img.src = e.target?.result as string
    }

    img.onload = async () => {
      // 创建canvas进行图片处理
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      
      // 设置canvas尺寸为头像容器大小
      canvas.width = 88
      canvas.height = 88

      // 计算裁剪区域，确保图片填充整个区域
      const size = Math.min(img.width, img.height)
      const startX = (img.width - size) / 2
      const startY = (img.height - size) / 2

      // 绘制裁剪后的图片
      ctx?.drawImage(
        img,
        startX, startY, size, size,
        0, 0, canvas.width, canvas.height
      )

      // 转换为base64格式并更新预览
      const resizedImage = canvas.toDataURL('image/jpeg', 0.8)
      avatarUrl.value = resizedImage

      try {
        isUploading.value = true
        // 模拟上传延迟
        await new Promise(resolve => setTimeout(resolve, 1500))
        // TODO: 实现实际的图片上传逻辑
        // const formData = new FormData()
        // formData.append('avatar', dataURLtoBlob(resizedImage))
        // const response = await fetch('/api/upload-avatar', {
        //   method: 'POST',
        //   body: formData
        // })
        // const data = await response.json()
        // avatarUrl.value = data.url
      } catch (error) {
        console.error('上传头像失败:', error)
        alert('上传头像失败，请重试')
      } finally {
        isUploading.value = false
      }
    }

    reader.readAsDataURL(file)
  }
}

onMounted(() => {
  // 从 sessionStorage 获取用户信息
  username.value = sessionStorage.getItem('username') || '咖啡爱好者'
  userId.value = sessionStorage.getItem('userId') || 'LDC80085211'
  // 获取保存的头像URL
  const savedAvatar = sessionStorage.getItem('avatarUrl')
  if (savedAvatar) {
    avatarUrl.value = savedAvatar
  }
})

const handleLogout = () => {
  // 清除登录状态
  sessionStorage.removeItem('isLoggedIn')
  sessionStorage.removeItem('username')
  sessionStorage.removeItem('userId')
  
  // 提示用户已退出
  alert('已退出登录')
  
  // 跳转到登录页
  router.push('/login')
}

const navigateToAddress = () => {
  // 跳转到地址管理页面
  router.push('/address')
}
//消息页面
const message=()=>{
  router.push('/Myother/message')
}
//帮助中心页面
const Translation=()=>{
  router.push('/Myother/Translation')
}
//关于我们页面
const About=()=>{
  router.push('/Myother/About')
}

//地址管理页面
const addresstwo = () => {
  // 跳转到地址管理页面
  router.push('/address')
}

// 会员特权页面
const member = () => {
  // 跳转到会员特权页面
  router.push('/Myother/member')
}

//积分商城页面
const Integral = () => {
  // 跳转到积分商城页面
  router.push('/Myother/integral')
}

//优惠卷页面
const Coupons = () => {
  // 跳转到优惠卷页面
  router.push('/Myother/Coupons')
}

//设置和上转图片页面
const set = () => {
  console.log('@!31');
  
  // 跳转到设置页面
  router.push('/setone')
}

// 我的订单页面
const over=()=>{
  router.push('/shopping/over')
}

//待付款页面
const payment=()=>{
  router.push('/shopping/payment')
}

//评价页面
const appraise=()=>{
  router.push('/shopping/appraise')
}
</script>

<style scoped>
.profile-container {
  padding: 0 0 80px 0;
  background-color: #f8f9fa;
  min-height: 1000px;
  max-width: 1000px;
  margin: 0 auto;
}

/* 用户信息头部 */
.user-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40px 28px;
  background: linear-gradient(120deg, #4f46e5 0%, #7c3aed 100%);
  color: white;
  border-radius: 0 0 36px 36px;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 24px;
}

.avatar {
  position: relative;
  width: 88px;
  height: 88px;
  border-radius: 50%;
  overflow: hidden;
  border: 4px solid rgba(255, 255, 255, 0.4);
  transition: transform 0.3s ease;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.user-details h2 {
  font-size: 26px;
  margin: 0 0 10px 0;
  font-weight: 700;
  letter-spacing: 0.5px;
}

.user-id {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
  letter-spacing: 0.3px;
}

.setting-icon {
  font-size: 28px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.setting-icon:hover {
  transform: rotate(30deg);
}

/* 会员卡样式 */
.member-card {
  margin: -40px 20px 24px;
  padding: 6px;
  background: linear-gradient(45deg, #1a1a1a, #333333);
  border-radius: 24px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
  transition: transform 0.3s ease;
}

.member-card:hover {
  transform: translateY(-5px);
}

.card-content {
  border-radius: 20px;
  padding: 24px;
  background-color: #222222;
  color: white;
  position: relative;
  overflow: hidden;
}

.card-content::before {
  content: '';
  position: absolute;
  top: -30px;
  left: -30px;
  width: 200px;
  height: 200px;
  background: radial-gradient(circle, rgba(255,255,255,0.2) 0%, transparent 70%);
  z-index: 1;
}

.card-logo {
  margin-bottom: 20px;
}

.logo-text {
  font-size: 26px;
  font-weight: 800;
  letter-spacing: 2px;
  color: #ffd700;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.card-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;
}

.points, .level {
  display: flex;
  flex-direction: column;
}

.point-value, .level-value {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 8px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.point-label, .level-label {
  font-size: 14px;
  opacity: 0.9;
  letter-spacing: 0.5px;
}

.card-bottom {
  display: flex;
  justify-content: flex-end;
}

.card-number {
  font-size: 16px;
  letter-spacing: 3px;
  opacity: 0.8;
}

/* 订单区域 */
.order-section {
  margin: 0 20px 24px;
  background-color: white;
  border-radius: 20px;
  padding: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  color: #1a1a1a;
}

.view-all {
  font-size: 15px;
  color: #6366f1;
  font-weight: 500;
}

.order-status {
  display: flex;
  justify-content: space-between;
}

.status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  transition: transform 0.2s ease;
}

.status-item:hover {
  transform: translateY(-3px);
}

.status-icon {
  font-size: 28px;
  margin-bottom: 10px;
}

.status-text {
  font-size: 14px;
  color: #4b5563;
  font-weight: 500;
}

/* 功能菜单 */
.function-menu {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 12px;
  margin: 0 20px 24px;
  background-color: white;
  border-radius: 20px;
  padding: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 0;
  cursor: pointer;
  transition: all 0.3s ease;
}

.menu-item:hover {
  transform: translateY(-3px);
}

.menu-icon {
  font-size: 28px;
  margin-bottom: 10px;
}

.menu-text {
  font-size: 14px;
  color: #4b5563;
  font-weight: 500;
}

/* 设置菜单 */
.settings-menu {
  margin: 0 20px 24px;
  background-color: white;
  border-radius: 20px;
  padding: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.settings-list {
  display: flex;
  flex-direction: column;
}

.settings-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.2s ease;
}

.settings-item:hover {
  background-color: #f8f9fa;
  padding-left: 10px;
}

.settings-item:last-child {
  border-bottom: none;
}

.item-name {
  font-size: 16px;
  color: #1f2937;
  font-weight: 500;
}

.item-arrow {
  color: #9ca3af;
  font-weight: bold;
}

.logout {
  color: #ef4444;
  font-weight: 600;
}
</style>